package com.lanou3g.dllo.baidumusic.mine.localmusic;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou3g.dllo.baidumusic.R;
import com.lanou3g.dllo.baidumusic.base.BaseFragment;
import com.lanou3g.dllo.baidumusic.database.MyFavorite;
import com.lanou3g.dllo.baidumusic.database.SingleLiteOrm;
import com.lanou3g.dllo.baidumusic.event.IndexEvent;
import com.lanou3g.dllo.baidumusic.event.SongIdEvent;
import com.lanou3g.dllo.baidumusic.main.playmusic.PlaymusicBean;
import com.lanou3g.dllo.baidumusic.tools.MyRvOnClickListener;
import com.lanou3g.dllo.baidumusic.tools.PlaylistManager;
import com.litesuits.orm.db.assit.QueryBuilder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by dllo on 16/7/7.
 */

public class LocalMusicFragment extends BaseFragment {

    private ArrayList<LocalMusicBean> localMusicBeen;
    private LocalMusicAdapter localMusicAdapter;
    private ListView localMusicListView;
    private ImageView localMusicReturn;
    private PopupWindow popupWindow;

    @Override
    public int setLayout() {
        return R.layout.fragment_localmusic;
    }

    @Override
    public void initView(View view) {
        localMusicAdapter = new LocalMusicAdapter(context);
        localMusicListView = (ListView) view.findViewById(R.id.localmusic_listview);
        // 给listView设置长按删除监听
        localMusicListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                SingleLiteOrm.getSingleLiteOrm().getLiteOrm().delete(localMusicBeen.get(position));
                localMusicAdapter.setDatas(SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(LocalMusicBean.class));
                // 内部删除发送广播刷新我的界面最近播放的歌曲数
                Intent intent = new Intent(context.getPackageName() + ".DELETEREFRESH");
                context.sendBroadcast(intent);
                return false;
            }
        });

        // 返回键
        localMusicReturn = (ImageView) view.findViewById(R.id.localmusic_return);
        localMusicReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag("LocalMusicFragment")).commit();
                getFragmentManager().beginTransaction().show(getFragmentManager().findFragmentByTag("MainFragment")).commit();
            }
        });
    }

    @Override
    public void initData() {

        localMusicBeen = new ArrayList<>();
        // 添加到数据库
        if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(LocalMusicBean.class).size() != 0) {
            for (LocalMusicBean localMusicBean : SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(LocalMusicBean.class)) {
                localMusicBeen.add(localMusicBean);
            }
            localMusicAdapter.setDatas(localMusicBeen);
            localMusicListView.setAdapter(localMusicAdapter);
        }

        localMusicAdapter.setMyRvOnClickListener(new MyRvOnClickListener() {
            @Override
            public void onClick(int position) {
                popMore(localMusicBeen, position);
            }
        });
    }

    // 进入popWindow界面
    private void popMore(final ArrayList<LocalMusicBean> datas, final int position) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_localmusicpop, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(localMusicListView, Gravity.BOTTOM, 0, 0);
        // 设置返回键可使popWindow关闭
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        ImageView popLove = (ImageView) view.findViewById(R.id.localmusic_love);
        ImageView popDelete = (ImageView) view.findViewById(R.id.localmusic_delete);
        ImageView popShare = (ImageView) view.findViewById(R.id.localmusic_share);
        FrameLayout empty = (FrameLayout) view.findViewById(R.id.localmusic_replace);
        TextView popTitle = (TextView) view.findViewById(R.id.localmusic_poptitle);
        popTitle.setText(datas.get(position).getTitle());
        // 条件查询
        QueryBuilder<MyFavorite> queryBuilder = new QueryBuilder<>(MyFavorite.class);
        queryBuilder.whereEquals("title", datas.get(position).getTitle());
        if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilder).size() == 0) {
            popLove.setImageResource(R.mipmap.pop_love_normal);
        } else {
            popLove.setImageResource(R.mipmap.pop_love_checked);
        }

        // 点击空白处关闭popWindow
        empty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        // 喜欢的点击事件
        popLove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryBuilder<MyFavorite> queryBuilder = new QueryBuilder<>(MyFavorite.class);
                queryBuilder.whereEquals("title", datas.get(position).getTitle());
                if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilder).size() == 0) {
                    SingleLiteOrm.getSingleLiteOrm().getLiteOrm().insert(new MyFavorite(datas.get(position).getTitle(), datas.get(position).getAuthor()));
                    Toast.makeText(context, "已添加到我喜欢的单曲", Toast.LENGTH_SHORT).show();
                    // 刷新我的界面我喜欢的单曲的歌曲数
                    Intent intent = new Intent(context.getPackageName() + ".REFRESHMYFAVORITE");
                    context.sendBroadcast(intent);
                } else {
                    SingleLiteOrm.getSingleLiteOrm().getLiteOrm().delete(SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilder));
                    Toast.makeText(context, "已取消喜欢", Toast.LENGTH_SHORT).show();
                }
                popupWindow.dismiss();
                // 取消喜欢的时候发广播刷新我的界面我喜欢的单曲的歌曲数
                Intent intent = new Intent(context.getPackageName() + ".REFRESHMYFAVORITE");
                context.sendBroadcast(intent);
            }

        });

        // 删除监听
        popDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SingleLiteOrm.getSingleLiteOrm().getLiteOrm().delete(localMusicBeen.get(position));
                localMusicAdapter.setDatas(SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(LocalMusicBean.class));
//                context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,MediaStore.Audio.Media.TITLE + " = ?",new String[]{String.valueOf()} )
                popupWindow.dismiss();
                Intent intent = new Intent(context.getPackageName() + ".DELETEREFRESH");
                context.sendBroadcast(intent);
            }
        });

        // 分享监听
        popShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

                ShareSDK.initSDK(context);
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                oks.setTitle("分享");
                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                oks.setTitleUrl("http://sharesdk.cn");
                // text是分享文本，所有平台都需要这个字段
                oks.setText("项目测试文本");
                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl("http://sharesdk.cn");
                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("项目测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite(getString(R.string.app_name));
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");
                // 启动分享GUI
                oks.show(context);
            }
        });

    }

}
